# Script to run QAP
library(sna)
library(doParallel)
library(doRNG)

# Load the followers adjacency matrix
y_f <- readRDS("processed_data/followers_adjacencyMatrix.Rds")
y_r <- readRDS("processed_data/retweets_adjacencyMatrix.Rds")
y_m <- readRDS("processed_data/mentions_adjacencyMatrix.Rds")
# Load the predicting matrix 
load("processed_data/QAP_predicting_matrices.RData")


# Parallel implementation to run QAP
#cl <- makeCluster(2, outfile="")  #11
#registerDoParallel(cl)
#set.seed(10)
#system.time(qap_res <- foreach(i=1:2,.packages=c("sna", "doRNG")) %dorng% {
#  netlm(y, predicting_matrices, reps=2)
#})
#stopCluster(cl)

diag(y_f) <- NA
diag(y_r) <- NA
diag(y_m) <- NA

y_vf <- 1*(c(y_f) > 0)
y_vr <- 1*(c(y_r) > 0)
y_vm <- 1*(c(y_m) > 0)


Var.names <-c("State_Similarity",
               "Party_Similarity",
               "Chamber_Similarity",
               "Gender_Similarity",
               "Race_Similarity",
               "Difference_in_Legislatures_Profeshionalism",
               "Dem_Sender_Effect",
               "Rep_Sender_Effect",
               "House_Sender_Effect",
               "Female_Sender_Effect",
               "Profesh_Sender_Effect",
               "Black_Sender_Effect",
               "Latino_Sender_Effect",
               "Asian_Sender_Effect",
               "Mena_Sender_Effect",
               "Multi_Sender_Effect",
               "Native_Sender_Effect",
               "Democrat_Receiver_Effect",
               "Republican_Receiver_Effect",
               "House_Receiver_Effect",
               "Female_Receiver_Effect",
               "Profesh_Receiver_Effect",
               "Black_Receiver_Effect",
               "Latino_Receiver_Effect",
               "Asian_Receiver_Effect",
               "Mena_Receiver_Effect",
               "Multi_Receiver_Effect",
               "Native_Receiver_Effect",
               "Same_Party_Same_State",
               "Same_Chamber_Same_State",
               "Same_Gender_Same_State",
               "Same_Race_Same_State",
               "Contiguous_States")

for(i in 1:length(Var.names)){
  xi <- predicting_matrices[i,,]
  diag(xi) <- NA
  print(sum(is.na(xi)))
  if(i == 1){
    xdf <- cbind(c(xi))
  }
  if(i > 1){
    xdf <- cbind(xdf,cbind(c(xi)))
  }
}

send_id <- matrix(1:nrow(y_f),nrow(y_f),nrow(y_f))
rec_id <- t(send_id)
diag(send_id) <- NA
diag(rec_id) <- NA

xdf <- cbind(xdf,c(send_id),c(rec_id))

xdf <- data.frame(xdf)

names(xdf) <- c(Var.names,c("send_id","rec_id"))

xydf <- data.frame(y_vf,y_vm,y_vr,xdf)

xynd <- na.omit(xydf)

library(dplyr)

## Mean
summary_table <- xynd %>%
  group_by(State_Similarity,Party_Similarity) %>%
  summarize(dyads = n(),follow_ties = sum(y_vf),rt_ties = sum(y_vr),mention_ties = sum(y_vm))

library(xtable)
xt <- xtable(summary_table)
print(xt,file="state_party_table.txt")


